package com.bigflexlib.x.mx.styles
{

	import com.bigflexlib.core.dependency.DependencyHelper;
	import com.bigflexlib.core.dependency.DependencySpec;
	import com.bigflexlib.x.mx.core.IMXMLObject.AbstractMXMLObject;
	
	import mx.styles.IStyleClient;



	/**
	 * 
	 * 
	 * 
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */
	public class StyleBinding extends AbstractMXMLObject
	{
		


		private var dh:DependencyHelper;



		////////////////////////////////////////
		// target
		////////////////////////////////////////

		private var targetSpec:DependencySpec = new DependencySpec( "target", "*" );
		[Bindable("targetChanged")]
		/**
		 * 
		 * The IStyleClient to which the style must be applied.
		 * If no value is passed then the surrounding MXML document is used as target.
		 * 
		 * @return 
		 * 
		 */		
		public function get target( ):IStyleClient
		{
			return dh.getDependencyValue( targetSpec ) as IStyleClient;
		}
		
		public function set target( v:IStyleClient ):void
		{
			dh.setDependencyValue( targetSpec, v );
		}
		



		////////////////////////////////////////
		// style
		////////////////////////////////////////

		private var styleSpec:DependencySpec = new DependencySpec( "style", "*" );
		[Bindable("styleChanged")]
		public function get style( ):String
		{
			return dh.getDependencyValue( styleSpec ) as String;
		}
		
		public function set style( v:String ):void
		{
			dh.setDependencyValue( styleSpec, v );
		}





		////////////////////////////////////////
		// value
		////////////////////////////////////////
		private var valueSpec:DependencySpec = new DependencySpec( "value", "*" );
		[Bindable("valueChanged")]
		public function get value( ):*
		{
			return dh.getDependencyValue( valueSpec );
		}
		
		public function set value( v:* ):void
		{
			dh.setDependencyValue( valueSpec, v );
		}







		public function StyleBinding( )
		{
		
			dh = new DependencyHelper( this, update );
		
		}






		
		private function update( ):void
		{
			
			// are we ready?
			
			if ( this.document == null ) // not initialized
			{
				return;
			}
			
			
			// define the target
			
			var t:IStyleClient = this.target;
			if ( t == null )
			{
				// this way we make target optional
				t = this.document as IStyleClient;			
			}			


			if ( t == null )
				return;
			
			
			try
			{
				t.setStyle( this.style, this.value );
			}
			catch ( e:Error )
			{
			
			}
			
		}












		
		
		
	}


}